package info.wangyuan.agent.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据脱敏工具类
 *
 * @author Albert
 */
@Slf4j
public class DesensitizeUtil {

    private DesensitizeUtil() {
    }

    /**
     * QQ邮箱脱敏
     */
    public static String maskEmail(String email) {
        if (StrUtil.isBlank(email)) {
            log.warn("邮箱不能为空");
            return email;
        }
        int atIndex = email.indexOf("@");
        if (atIndex <= 0) {
            log.warn("邮箱格式不正确: {}", email);
            return email;
        }

        String domain = email.substring(atIndex).toLowerCase();
        if (!"@qq.com".equals(domain)) {
            log.warn("仅支持QQ邮箱脱敏: {}", email);
            return email;
        }

        String prefix = email.substring(0, atIndex);
        int len = prefix.length();
        if (len >= 5) {
            return prefix.substring(0, 5) + "***" + domain;
        }
        if (len >= 2) {
            return prefix.charAt(0) + "***" + prefix.charAt(len - 1) + domain;
        }
        return prefix + "***" + domain;
    }

    /**
     * API Key 脱敏
     */
    public static String maskApiKey(String apiKey) {
        if (StrUtil.isBlank(apiKey)) {
            log.warn("API Key 为空");
            return apiKey;
        }

        String prefix = "";
        String realKey = apiKey;

        // 处理 sk- 或其他前缀
        int dashIndex = apiKey.indexOf("-");
        if (dashIndex > 0 && dashIndex < 4) {
            prefix = apiKey.substring(0, dashIndex + 1);
            realKey = apiKey.substring(dashIndex + 1);
        }

        int len = realKey.length();
        if (len <= 2) {
            return prefix + realKey.charAt(0) + "*";
        }
        if (len <= 7) {
            return prefix + realKey.charAt(0) + "***" + realKey.charAt(len - 1);
        }
        return prefix + realKey.charAt(0) + "****" + realKey.substring(len - 3);
    }

    /**
     * 微信用户 OpenID 脱敏
     */
    public static String maskWeChatOpenId(String openId) {
        if (StrUtil.isBlank(openId)) {
            log.warn("OpenID 为空");
            return openId;
        }

        int len = openId.length();
        if (len <= 4) {
            // 太短时直接用 * 代替
            return "*".repeat(len);
        }

        // 保留前 3 位和后 3 位，中间用 *** 隐藏
        return openId.substring(0, 3) + "***" + openId.substring(len - 3);
    }

}
